import os
import random
import math
import time
import creater.creatorMain as cr
import cv2 as cv
import numpy as np

width = 1024
height = 1280


def point_to_center_dis(point, center_):
    return math.sqrt(math.pow((point[0] - center_[0]), 2) + math.pow((point[1] - center_[1]), 2))


def add_salut_noisy(res, center, xmin, xmax, ymin, ymax, max_radius, min_radius):
    for ii in range(xmin, xmax):
        for jj in range(ymin, ymax):
            point_ = [ii, jj]
            if point_to_center_dis(point_, center) <= max_radius + 2:
                if point_to_center_dis(point_, center) >= min_radius - 2:
                    if np.random.rand() < 1:
                        if np.random.rand() < 0.5:
                            res[jj, ii] = random.randint(0, 100)
                        else:
                            res[jj, ii] = random.randint(130, 200)


def create_img_by_img():
    # 读取原始图像并转换为灰度图像
    image = cv.imread('/disk/data4T/yolov7_test/yolo_v7/realData/2305251/circle+circlering/1.bmp', cv.IMREAD_GRAYSCALE)
    # 获取原始图像的灰度值分布直方图
    hist = cv.calcHist([image], [0], None, [256], [0, 256])
    # 计算累积直方图
    cdf = hist.cumsum()
    # 归一化累积直方图
    cdf_normalized = cdf / cdf.max()
    # 生成随机数列
    random_values = np.random.rand(image.shape[0] * image.shape[1])
    # 根据灰度值分布对随机数列进行排序
    sorted_values = np.interp(random_values, cdf_normalized, np.arange(0, 256))
    # 将排序后的值重塑为与原始图像相同大小的矩阵
    sorted_image = np.reshape(sorted_values, image.shape).astype(np.uint8)
    return sorted_image


def creator_img(_file_path, _res_path):
    random_img = create_img_by_img()
    color = 255
    img_ = 255 * np.zeros((width, height), dtype=np.uint8)
    img_2 = 255 * np.zeros((width, height), dtype=np.uint8)
    img_[:] = color
    img_2[:] = color
    max_radius = random.randint(145, 160)
    min_radius = max_radius - random.randint(20, 30)
    inner_circle_radius = min_radius - random.randint(20, 40)
    x = random.randint(max_radius, width - 2 * max_radius)
    y = random.randint(max_radius, height - 2 * max_radius)
    center = [y, x]

    xmin = center[0] - max_radius
    ymin = center[1] - max_radius
    xmax = center[0] + max_radius
    ymax = center[1] + max_radius

    centerx = center[0] / height
    centery = center[1] / width
    dx = (2 * min_radius) / height
    dy = (2 * min_radius) / width  # ring--inner circle

    dx2 = (2 * max_radius) / height
    dy2 = (2 * max_radius) / width  # ring--outer circle

    dx3 = (2 * inner_circle_radius) / height
    dy3 = (2 * inner_circle_radius) / width

    _res_path.write("2" + ' ')
    _res_path.write(str(centerx) + ' ')
    _res_path.write(str(centery) + ' ')
    _res_path.write(str(dx) + ' ')
    _res_path.write(str(dy) + ' ' + '\n')  # ring--inner circle

    _res_path.write("1" + ' ')
    _res_path.write(str(centerx) + ' ')
    _res_path.write(str(centery) + ' ')
    _res_path.write(str(dx2) + ' ')
    _res_path.write(str(dy2) + ' ' + '\n')  # ring--outer circle

    _res_path.write("0" + ' ')
    _res_path.write(str(centerx) + ' ')
    _res_path.write(str(centery) + ' ')
    _res_path.write(str(dx3) + ' ')
    _res_path.write(str(dy3) + ' ' + '\n')

    blcakcolor = random.randint(0, 100)
    cv.circle(img_, (center[0], center[1]), max_radius, blcakcolor, 0, cv.LINE_AA)
    cv.circle(img_2, (center[0], center[1]), min_radius, blcakcolor, 0, cv.LINE_AA)

    difference = cv.absdiff(img_, img_2)
    _, threshold = cv.threshold(difference, 20, 255, cv.THRESH_BINARY)
    for ii in range(xmin, xmax):
        for jj in range(ymin, ymax):
            point_ = [ii, jj]
            if point_to_center_dis(point_, center) <= max_radius:
                if point_to_center_dis(point_, center) >= min_radius:
                    threshold[jj, ii] = 230
    res = cv.add(threshold, random_img)
    inner_circle_color = random.randint(30, 50)
    cv.circle(res, (center[0], center[1]), inner_circle_radius, inner_circle_color, -1, cv.LINE_AA)
    add_salut_noisy(res, center, xmin, xmax, ymin, ymax, max_radius, min_radius)
    add_salut_noisy(res, center, center[0] - inner_circle_radius, center[0] + inner_circle_radius,
                    center[1] - inner_circle_radius, center[1] + inner_circle_radius, inner_circle_radius, 0)
    # add bandia img
    add_bandian_result = cr.add_bandian_to_originImg(res, _res_path)
    # 中值
    # blurred = creatorMain.add_median_filter(res, kernel_size=3)
    # 均值
    # blurred = creatorMain.add_mean_filter(add_bandian_result, kernel_size=3)
    # 高斯
    ksize = (5, 5)
    sigma = 0
    blurred2 = cv.GaussianBlur(add_bandian_result, ksize, sigma)
    # cv.rectangle(blured2, (xmin, ymin), (xmax, ymax), 255, 5)
    cv.imwrite(_file_path, blurred2)

    # cv.imshow("omg", blurred2)
    # cv.waitKey(0)
    # cv.imshow("omg1", blurred2)
    # cv.waitKey(0)
    # cv.imshow("res", random_img)
    # cv.waitKey(0)

# /home/mikoptik/yolov7_test/yolo_v7/match_circle

if __name__ == '__main__':
    root_dir = "/home/mikoptik/yolov7_test/yolo_v7/match_circle"  # 23_07_28run  match_circle/
    dir_num = 1
    img_num = 5000
    for i in range(1, dir_num + 1):
        folder_path = os.path.join(root_dir, str(i))
        res_path_d = os.path.join(folder_path, "res")
        # txt_path = os.path.join(folder_path, str(i) + '.txt')
        print(i, " begin")
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
        if not os.path.exists(res_path_d):
            os.makedirs(res_path_d)
        # file = open(txt_path, 'w')
        for j in range(1, img_num + 1):
            start_time = time.time()
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
            file_path = os.path.join(folder_path, "ring+circle" + str(j) + '.bmp')
            res_path = os.path.join(res_path_d, "ring+circle" + str(j) + ".txt")
            res_file = open(res_path, 'w')
            creator_img(file_path, res_file)
            end_time = time.time()
            if j % 100 == 0:
                print(j, "-->finish", "time-->", end_time - start_time, '/pcs')
